package com.kgc.kmall.kmallorderservice.service;

import com.kgc.kmall.bean.OmsOrder;
import com.kgc.kmall.bean.OmsOrderExample;
import com.kgc.kmall.bean.OmsOrderItem;
import com.kgc.kmall.kmallorderservice.mapper.OmsOrderItemMapper;
import com.kgc.kmall.kmallorderservice.mapper.OmsOrderMapper;
import com.kgc.kmall.service.OrderService;
import com.kgc.kmall.util.RedisUtil;
import org.apache.dubbo.config.annotation.Service;
import redis.clients.jedis.Jedis;

import javax.annotation.Resource;
import java.util.List;
import java.util.UUID;

@Service
public class OrderServiceImpl implements OrderService {
    @Resource
    RedisUtil redisUtil;
    @Resource
    OmsOrderMapper omsOrderMapper;
    @Resource
    OmsOrderItemMapper omsOrderItemMapper;
    @Override
    public String genTradeCode(Long aLong) {
        Jedis jedis = redisUtil.getJedis();
        String tradeKey = "user:"+aLong+":tradeCode";
        String tradeCode = UUID.randomUUID().toString();
        jedis.setex(tradeKey,60*15,tradeCode);
        jedis.close();
        return tradeCode;
    }

    @Override
    public String checkTradeCode(Long aLong, String tradeCode) {
        Jedis jedis = redisUtil.getJedis();
        String tradeKey = "user:"+aLong+":tradeCode";
        String s = jedis.get(tradeKey);
        jedis.del(tradeKey);
        if(tradeCode.equals(s)){
            jedis.close();
            return "success";
        }else{
            jedis.close();
            return "fail";
        }

    }

    @Override
    public void saveOrder(OmsOrder omsOrder) {
        omsOrderMapper.insertSelective(omsOrder);
        Long id = omsOrder.getId();
        //保存订单详情
        List<OmsOrderItem> orderItems = omsOrder.getOrderItems();
        for (OmsOrderItem orderItem : orderItems) {
            orderItem.setOrderId(id);
            omsOrderItemMapper.insertSelective(orderItem);
        }
    }

    @Override
    public OmsOrder getOrderByOutTradeNo(String outTradeNo) {
        OmsOrderExample example=new OmsOrderExample();
        example.createCriteria().andOrderSnEqualTo(outTradeNo);
        List<OmsOrder> omsOrders = omsOrderMapper.selectByExample(example);
        if(omsOrders!=null&&omsOrders.size()>0){
            return omsOrders.get(0);
        }
        return null;
    }

    @Override
    public void updateOrder(OmsOrder omsOrder) {
        OmsOrderExample example=new OmsOrderExample();
        example.createCriteria().andOrderSnEqualTo(omsOrder.getOrderSn());
        omsOrder.setStatus(1);
        omsOrderMapper.updateByExampleSelective(omsOrder,example);
    }
}
